package cn.edu.hhu.teacher;

import cn.edu.hhu.teacher.bean.Course;
import cn.edu.hhu.teacher.bean.Teacher;
import cn.edu.hhu.teacher.service.CourseService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/teacher/course")
public class CourseServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        CourseService courseService = new CourseService();
        Course course = courseService.get((Teacher) request.getSession().getAttribute("teacher"), request.getParameter("cid"));
        if (course == null) {
            response.sendRedirect(request.getContextPath() + "/teacher/index");
            return;
        }
        String input_verifycode = request.getParameter("verifycode");
        String true_verifycode = (String) request.getSession().getAttribute("verifycode");
        if (true_verifycode == null || !true_verifycode.equalsIgnoreCase(input_verifycode)) {
            request.setAttribute("msg", "验证码错误！");
            doGet(request, response);
            return;
        }
        if (courseService.delete(course)) {
            response.sendRedirect(request.getContextPath() + "/teacher/index");
        } else {
            request.setAttribute("msg", "删除课程失败！");
            doGet(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        CourseService courseService = new CourseService();
        Course course = courseService.get((Teacher) request.getSession().getAttribute("teacher"), request.getParameter("cid"));
        if (course == null) {
            response.sendRedirect(request.getContextPath() + "/teacher/index");
            return;
        }
        request.setAttribute("course", course);
        request.getRequestDispatcher("/WEB-INF/view/teacher/course.jsp").forward(request, response);
    }
}
